package com.demo.security.service.impl;


import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheRefresh;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.CacheUpdate;
import com.alicp.jetcache.anno.CreateCache;
import com.demo.security.model.SysUser;
import com.demo.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserCacheServiceImpl {

    @Autowired
    private UserService userService;

    @CreateCache(name="jetCache",expire = 3600,cacheType= CacheType.LOCAL,timeUnit = TimeUnit.MINUTES)
    private Cache<String, SysUser> userCache;

    @CreateCache(name="jetCache",expire = 3600,cacheType= CacheType.LOCAL,timeUnit = TimeUnit.MINUTES)
    private Cache<String, SysUser> userCacheByName;

    @PostConstruct
    public void init(){
        List<SysUser> sysUsers = userService.getUser();
        sysUsers.forEach(sysUser -> {
            userCache.put(sysUser.getCode(),sysUser);
            userCacheByName.put(sysUser.getUsername(),sysUser);
        });
    }


    public SysUser getSysUserByName(String name ){
        return userCacheByName.get(name);
    }

    public SysUser getSysUserByCode(String code ){
        return userCache.get(code);
    }
}
